package com.zhuangjie.rider.ws.interceptor;

import com.zhuangjie.mvc.ws.Interceptor.WebSocketInterceptor;
import com.zhuangjie.mvc.ws.annotation.WSInterceptor;
import com.zhuangjie.security.helper.JwtHelper;
import com.zhuangjie.security.helper.config.td.AllTokenDataKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

@WSInterceptor(rule = "/rider")
public class GlobalWSInterceptor implements WebSocketInterceptor {
    private final String  TOKEN = "token";

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public String onRegister(WebSocketSession session) throws Exception {
        Map<String,String> params = parseUrlParams(session.getUri().getQuery());
        String token =  params == null?null:params.get(TOKEN);
        if (token == null) {
            throw new RuntimeException("没有传入token参数，无法识别身份！");
        }
        Map<String, Object> tokenDataMap = jwtHelper.authentication(token, false, false, true);
        return  tokenDataMap.get(AllTokenDataKeys.USER_ID_KEY)+"";
    }

    /**
     * 解析url参数
     *
     * @param query 查询
     * @return {@link Map}<{@link String}, {@link String}>
     */
    private Map<String, String> parseUrlParams(String query) {
        if (query == null || query.isEmpty()){
            return null;
        }
        Map<String, String> map = new HashMap<>();
        StringTokenizer st = new StringTokenizer(query, "&");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            int equalIndex = token.indexOf("=");
            String key = token.substring(0, equalIndex);
            String value = token.substring(equalIndex + 1);
            map.put(key, value);
        }
        return map;
    }


}
